<?php

require('../vendor/autoload.php');

use BitWasp\Bitcoin\Base58;
use BitWasp\Bitcoin\Key\PrivateKeyFactory;
use BitWasp\Bitcoin\Address\PayToPubKeyHashAddress;
use BitWasp\Bitcoin\Transaction\TransactionFactory;
use BitWasp\Bitcoin\Transaction\Factory\Signer;
use BitWasp\Bitcoin\transaction\TransactionOutput;
use BitWasp\Bitcoin\Serializer\Transaction\TransactionSerializer;
use BitWasp\Bitcoin\Network\NetworkFactory;
use BtcTool\Client;
use BtcTool\Credential;

function fund($spender,$amount){
  $addr = $spender->p2pkh->getAddress(NetworkFactory::bitcoinRegtest());
  $client = new Client('http://user:123456@127.0.0.1:18443');
  $txid = $client->exec('sendtoaddress',$addr,$amount)->result;
  $client->exec('generate',6);
  $tx = $client->exec('getrawtransaction',$txid,true)->result;
  foreach($tx->vout as $txo){
    if(in_array($addr,$txo->scriptPubKey->addresses))
        return ['txid'=>$txid,'vout'=>$txo->n,'value'=>$txo->value];
  }
}

function spend($utxo,$spender,$shop,$amount,$change){
  $tval = $amount * 100000000; //in satoshi
  $fee = 0.0001 * 100000000;
  var_dump($fee);
  $cval = intval($utxo['value']*100000000 - $tval - $fee);
  if($cval < 0) throw new Exception('utxo not enough!');

  
  $tx = TransactionFactory::build()
            ->input($utxo['txid'],$utxo['vout'])
            ->output($tval,$shop->p2pkh->getScriptPubKey())
            ->output($cval,$change->p2pkh->getScriptPubKey())
            ->get();

  $signer = new Signer($tx);
  $lock = new TransactionOutput(0,$spender->p2pkh->getScriptPubKey());
  $signed = $signer->sign(0,$spender->prv,$lock)    
            ->get();
   
  $serializer = new TransactionSerializer();
  $raw = $serializer->serialize($signed);

  return $raw->getHex();
}

function decode($rawtx){
  $client = new Client('http://user:123456@127.0.0.1:18443');
  $ret = $client->exec('decoderawtransaction',$rawtx);
  var_dump($ret);
}

function confirm($rawtx){
  $client = new Client('http://user:123456@127.0.0.1:18443');
  $txid = $client->exec('sendrawtransaction',$rawtx)->result;
  $client->exec('generate',6);
  return $txid;
}


$spender = Credential::new();
$shop = Credential::new();
$change = Credential::new();
$utxo = fund($spender,10);
$rawtx = spend($utxo,$spender,$shop,5,$change);
//echo $rawtx . PHP_EOL;
//decode($rawtx);
$txid = confirm($rawtx);
echo 'txid => ' . $txid . PHP_EOL;